import pickle
import base64
from django_redis import get_redis_connection
#------------------------合并购物车----------------------------
def get_carts(request,response,user):
    # 获取cookie数据
    cart_cookie = request.COOKIES.get('cart_cookie')
    if not  cart_cookie:
        return response
    #对购物车数据进行解密
    data_dict = pickle.loads(base64.b64decode(cart_cookie))
    # 判断购物车数据是否存在
    if data_dict is None:
        return response
    # 拆分购物车数据，形成hash和set形方便保存在redis中
    cart_dict = []
    cart_list = []
    cart_list_none = []
    for sku_id,sku_data in data_dict.items():
        cart_dict[sku_id] = sku_data['count']
        if sku_data['selected']:
            # 获取选中状态
            cart_list.append(sku_id)
        else:
            cart_list_none.append(sku_id)
    # 写入redis数据
    client = get_redis_connection('carts')
    # 写入hash数据
    client.hmset('carts_%s'%user.id,cart_dict)
    if cart_list:
        # cart_list存储的是需要选中的sku_id,所以需要全部添加到集合
        client.sadd('carts_selected_%d'%user.id,*cart_list)
    if cart_list_none:
        # cart_list存储的是未选中的sku_id，所以需要全部从集合删除
        client.srem('carts_selected_%d'%user.id,*cart_list_none)
    # 删除cookie
    response.delete_cookie('care_cookie')
    return response

